package com.smiletrain.activities;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import com.smiletrain.R;
import com.smiletrain.activities.base.AbstractActivity;
import com.smiletrain.util.AdminCasos;
import com.smiletrain.util.Constantes;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;

public class PreFotosActivity extends AbstractActivity {
	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		if(caso.getNumFotografias() == 1) {
			
			setContentView(R.layout.prefotos_view_1);
			
			if(!caso.getPreFotos().getPathImage1().equals("")){
				ImageView pre1 = (ImageView) findViewById(R.id.bFrontal);
				MuestraFoto(caso.getPreFotos().getPathImage1(), pre1);
				toma1 = true;
			}

			iv1 = (ImageView) findViewById(R.id.bFrontal);
			
			if(caso.getPreFotos().getNameImage1().equals(""))
				realname1 = genFileName("frontal"); 
			else
				realname1 = caso.getPreFotos().getNameImage1();
			
			filename1 = Environment.getExternalStorageDirectory().getAbsolutePath()
					+ realname1;
			
			iv1.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					
					Uri output = Uri.fromFile(new File(filename1));
					
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					
					intent.putExtra(MediaStore.EXTRA_OUTPUT, output);

					startActivityForResult(intent, Constantes.ACTIVITY_TAKE_PICTURE_VIEW04_IMG01);
					
				}
				
			});
			
		} else {
			
			setContentView(R.layout.prefotos_view_2);
			
			if(!caso.getPreFotos().getPathImage1().equals("")){
				ImageView pre1 = (ImageView) findViewById(R.id.bFrontal);
				MuestraFoto(caso.getPreFotos().getPathImage1(), pre1);
				toma1 = true;
			}
			
			if(!caso.getPreFotos().getPathImage2().equals("")){
				ImageView pre2 = (ImageView) findViewById(R.id.bOral);
				MuestraFoto(caso.getPreFotos().getPathImage2(), pre2);
				toma2 = true;
			}
			
			iv1 = (ImageView) findViewById(R.id.bFrontal);
			
			if(caso.getPreFotos().getNameImage1().equals(""))
				realname1 = genFileName("frontal");
			else
				realname1 = caso.getPreFotos().getNameImage1();
			
			filename1 = Environment.getExternalStorageDirectory().getAbsolutePath()
					+ realname1;
			
			iv1.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					
					Uri output = Uri.fromFile(new File(filename1));
					
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					
					intent.putExtra(MediaStore.EXTRA_OUTPUT, output);

					startActivityForResult(intent, Constantes.ACTIVITY_TAKE_PICTURE_VIEW04_IMG01);
					
				}
				
			});
			
			iv3 = (ImageView) findViewById(R.id.bOral);
			
			if(caso.getPreFotos().getNameImage2().equals(""))
				realname3 = genFileName("oral");
			else
				realname3 = caso.getPreFotos().getNameImage2();
			
			filename3 = Environment.getExternalStorageDirectory().getAbsolutePath()
					+ realname3;
			
			iv3.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					
					Uri output = Uri.fromFile(new File(filename3));
					
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					
					intent.putExtra(MediaStore.EXTRA_OUTPUT, output);

					startActivityForResult(intent, Constantes.ACTIVITY_TAKE_PICTURE_VIEW04_IMG03);
					
				}
				
			});
		}		
		
		super.setFootLayout();
		
		ImageView siguiente = (ImageView) findViewById(R.id.bSiguiente);
        
        siguiente.setOnClickListener(new OnClickListener() {
        	
			@Override
			public void onClick(View v) {
				
				updateCaso();
				
				if(!AdminCasos.validarPreFotos(caso, PreFotosActivity.this)){
					Toast.makeText(PreFotosActivity.this, "Debe tomar las fotografías para poder continuar.", Toast.LENGTH_LONG).show();
				} else {
					Intent intent = new Intent(PreFotosActivity.this, RecordatorioActivity.class);
					startActivity(intent);
				}
			}
			
		});
        
	}
	
	@Override
	public void updateCaso() {
		if(!toma1){
			caso.getPreFotos().setPathImage1("");
			caso.getPreFotos().setNameImage1("");
		} else {
			caso.getPreFotos().setPathImage1(filename1);
			caso.getPreFotos().setNameImage1(realname1);
		}
		
		if(!toma2){
			caso.getPreFotos().setPathImage2("");
			caso.getPreFotos().setNameImage2("");
		} else {
			caso.getPreFotos().setPathImage2(filename3);
			caso.getPreFotos().setNameImage2(realname3);
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		switch (requestCode) {
			case Constantes.ACTIVITY_TAKE_PICTURE_VIEW04_IMG01:
				MuestraFoto(filename1, iv1);
				saveImage(filename1);
				toma1 = true;
				//MuestraFoto(imgFrontal1.getFileName(), imgFrontal1.getView());
				//view = (ImageView) findViewById(R.id.bFrontal1);
				//view.setImageBitmap(genImage(imgFrontal1.getFileName()));
				break;
			case Constantes.ACTIVITY_TAKE_PICTURE_VIEW04_IMG02:
				//MuestraFoto(filename2, iv2);
				break;
			case Constantes.ACTIVITY_TAKE_PICTURE_VIEW04_IMG03:
				MuestraFoto(filename3, iv3);
				saveImage(filename3);
				toma2 = true;
				break;
			default:
		}
		
	}
	
	private void MuestraFoto(String arch, ImageView view) {
		try {
			BitmapFactory.Options op = new BitmapFactory.Options();
			op.inJustDecodeBounds = true;
			int scale = 1;
			FileInputStream fd = new FileInputStream(arch);

			BitmapFactory.decodeFileDescriptor(fd.getFD(), null, op);
			
			if (op.outHeight > Constantes.IMAGE_MAX_SIZE || op.outWidth > Constantes.IMAGE_MAX_SIZE) {
				double d = Math.pow(2, (int) Math.round(Math.log(Constantes.IMAGE_MAX_SIZE / (double) Math.max(op.outHeight, op.outWidth)) / Math.log(0.5)));
				scale = (int) d;
			}
			
			op = new BitmapFactory.Options();
			op.inSampleSize = scale;

			view.setImageBitmap(BitmapFactory.decodeFileDescriptor(fd.getFD(),null,op));
			
			fd.close();
			
		} catch(Exception e) {
			Toast.makeText(this, e.toString(), Toast.LENGTH_LONG);
		}
	}
	
	private String genFileName(String aux) {
		Long date = new Date().getTime();
		String sdate = date.toString();
		String name = Constantes.IMAGE_PATH
				+ "imgst.pre." + aux + "."
				+ sdate.substring(sdate.length() - 6, sdate.length() - 2);
		name += ".jpg";
		return name;
	}
	
	@SuppressWarnings("unused")
	private Bitmap redimensionarImagenMaximo(Bitmap mBitmap, float newWidth, float newHeigth) {
		int width = mBitmap.getWidth();
		int height = mBitmap.getHeight();
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeigth) / height;

		Matrix matrix = new Matrix();

		matrix.postScale(scaleWidth, scaleHeight);

		return Bitmap.createBitmap(mBitmap, 0, 0, width, height, matrix, false);
	}
	
	private void saveImage(String pathfilename) {
		File dest = new File(pathfilename);

		Bitmap bitmap = buildBitmap(pathfilename);
		
		try {
		     FileOutputStream out = new FileOutputStream(dest);
		     bitmap.compress(Bitmap.CompressFormat.JPEG, 70, out);
		     out.flush();
		     out.close();
		} catch (Exception e) {
			Toast.makeText(this, e.toString(), Toast.LENGTH_LONG);
		}
		
		if(bitmap != null)
			bitmap.recycle();
	}
	
	private Bitmap buildBitmap(String arch) {
		Bitmap res = null;
		BitmapFactory.Options op = new BitmapFactory.Options();
		op.inJustDecodeBounds = true;

		try {
			
			FileInputStream fd = new FileInputStream(arch);
			BitmapFactory.decodeFileDescriptor(fd.getFD(), null, op);
			op = new BitmapFactory.Options();
		
			res = BitmapFactory.decodeFileDescriptor(fd.getFD(),null,op);
			
		} catch (IOException e) {
			Toast.makeText(this, e.toString(), Toast.LENGTH_LONG);
		}
		
		return res;
	}
	
	private ImageView iv1, iv3;
	private String filename1 = "", filename3 = "";
	private String realname1 = "", realname3 = "";
	private boolean toma1 = false, toma2 = false;
	
}
